import { create } from 'zustand';
import { devtools } from 'zustand/middleware';
import connectionService from '../services/connections';
import type { ConnectionDetail } from '../types/api';

interface ConnectionStore {
  // 状态
  connections: ConnectionDetail[];
  currentConnection: string | null;
  loading: boolean;
  error: string | null;
  
  // 操作方法
  fetchConnections: () => Promise<void>;
  createConnection: (data: { name: string; uri: string; set_as_default?: boolean }) => Promise<void>;
  deleteConnection: (connectionId: string) => Promise<void>;
  setCurrentConnection: (connectionId: string) => Promise<void>;
  checkConnectionHealth: (connectionId: string) => Promise<boolean>;
  reconnectConnection: (connectionId: string) => Promise<void>;
  reconnectAllConnections: () => Promise<void>;
  
  // 工具方法
  getConnectionById: (connectionId: string) => ConnectionDetail | undefined;
  getDefaultConnection: () => ConnectionDetail | undefined;
  clearError: () => void;
}

export const useConnectionStore = create<ConnectionStore>()(
  devtools(
    (set, get) => ({
      connections: [],
      currentConnection: localStorage.getItem('currentConnection'),
      loading: false,
      error: null,

      // 获取所有连接
      fetchConnections: async () => {
        set({ loading: true, error: null });
        try {
          console.log('开始获取连接列表...');
          const connections = await connectionService.listConnections();
          console.log('获取到的连接数据:', connections);
          console.log('连接数量:', connections?.length || 0);
          
          set({ connections, loading: false });
          console.log('连接列表已更新');
          
          // 检查当前连接是否仍然存在
          const { currentConnection } = get();
          if (currentConnection && !connections.find(conn => conn.name === currentConnection)) {
            // 如果当前连接不存在了，清除它
            console.log('当前连接已不存在，清除当前连接');
            set({ currentConnection: null });
            localStorage.removeItem('currentConnection');
          }
          
          // 如果没有当前连接且有可用连接，设置第一个为默认
          if (!currentConnection && connections.length > 0) {
            const defaultConn = connections.find(conn => conn.connected) || connections[0];
            if (defaultConn) {
              console.log('设置默认连接:', defaultConn.name);
              await get().setCurrentConnection(defaultConn.name);
            }
          }
        } catch (error: any) {
          console.error('获取连接列表失败:', error);
          set({
            error: error.message || '获取连接列表失败',
            loading: false
          });
        }
      },

      // 创建新连接
      createConnection: async (data) => {
        set({ loading: true, error: null });
        try {
          const newConnection = await connectionService.createConnection(data);
          
          // 更新连接列表
          const { connections } = get();
          set({ 
            connections: [...connections, newConnection], 
            loading: false 
          });
          
          // 如果是默认连接或第一个连接，设置为当前连接
          if (data.set_as_default || connections.length === 0) {
            await get().setCurrentConnection(newConnection.name);
          }
        } catch (error: any) {
          set({ 
            error: error.message || '创建连接失败', 
            loading: false 
          });
          throw error;
        }
      },

      // 删除连接
      deleteConnection: async (connectionId) => {
        set({ loading: true, error: null });
        try {
          await connectionService.deleteConnection(connectionId);
          
          // 更新连接列表
          const { connections, currentConnection } = get();
          const updatedConnections = connections.filter(conn => conn.name !== connectionId);
          
          set({ 
            connections: updatedConnections, 
            loading: false 
          });
          
          // 如果删除的是当前连接，清除当前连接
          if (currentConnection === connectionId) {
            set({ currentConnection: null });
            localStorage.removeItem('currentConnection');
          }
        } catch (error: any) {
          set({ 
            error: error.message || '删除连接失败', 
            loading: false 
          });
          throw error;
        }
      },

      // 设置当前连接
      setCurrentConnection: async (connectionId) => {
        set({ loading: true, error: null });
        try {
          // 设置为默认连接
          await connectionService.setDefaultConnection(connectionId);
          
          set({ 
            currentConnection: connectionId, 
            loading: false 
          });
          localStorage.setItem('currentConnection', connectionId);
        } catch (error: any) {
          set({ 
            error: error.message || '设置默认连接失败', 
            loading: false 
          });
          throw error;
        }
      },

      // 检查连接健康状态
      checkConnectionHealth: async (connectionId) => {
        try {
          const health = await connectionService.checkConnectionHealth(connectionId);
          return health.status === 'healthy';
        } catch (error) {
          return false;
        }
      },

      // 重新连接
      reconnectConnection: async (connectionId) => {
        set({ loading: true, error: null });
        try {
          await connectionService.reconnectConnection(connectionId);
          
          // 重新获取连接列表
          await get().fetchConnections();
        } catch (error: any) {
          set({ 
            error: error.message || '重新连接失败', 
            loading: false 
          });
          throw error;
        }
      },

      // 重新连接所有连接
      reconnectAllConnections: async () => {
        set({ loading: true, error: null });
        try {
          await connectionService.reconnectAllConnections();
          
          // 重新获取连接列表
          await get().fetchConnections();
        } catch (error: any) {
          set({ 
            error: error.message || '重新连接所有连接失败', 
            loading: false 
          });
          throw error;
        }
      },

      // 工具方法
      getConnectionById: (connectionId) => {
        const { connections } = get();
        return connections.find(conn => conn.name === connectionId);
      },

      getDefaultConnection: () => {
        const { connections } = get();
        return connections.find(conn => conn.connected);
      },

      clearError: () => {
        set({ error: null });
      },
    }),
    {
      name: 'connection-store',
    }
  )
);

// 选择器
export const useCurrentConnection = () => 
  useConnectionStore(state => state.currentConnection);

export const useConnections = () => 
  useConnectionStore(state => state.connections);

export const useConnectionLoading = () => 
  useConnectionStore(state => state.loading);

export const useConnectionError = () => 
  useConnectionStore(state => state.error);